<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/index.css">
</head>
<body>
    <div class="container">
        <div class="floor-top">
            <p>新年快乐</p>
            <p>楼主：球球</p>
            <p>新的一年、祝福大家新年快乐</p>
        </div>
        <form>
            <input id="nickName" placeholder="请输入您的昵称">
            <input id="content" placeholder="评论内容">
            <input type="button" id="addContentBtn" value="发表">
        </form>
        <ul id="ul">
        
        </ul>
    </div>
</body>
<script src="./js/jquery-1.12.4.js"></script>
<script src="./js/template-native.js"></script>
<script src="./js/index.js"></script>
<script type="text/html" id="myTemplate">
 <% for(let i = 0; i < commonts.length; i++){ %>
    <li uid=<%= commonts[i].id%>>
        <img src="./img/head.png"/>
        <div>
            <span><%= commonts[i].nickName%></span>
            <p class="time"> <%= commonts[i].dateTime%> &nbsp;<%= i+1%>层</p>
            <p><%= commonts[i].content%></p>
        </div>
        <button onClick="deleteCommont(<%= commonts[i].id%>)">删除</button>
    </li>
<% } %>
</script>
<script>
    function render(){
        $.ajax({
        url: "http://localhost:3000/commonts",
        type: "GET",
        success: function(data){
            console.log(data)
            $("#ul").html(template("myTemplate", {'commonts':data}));
        }
        })  
    }

    render();

    // 添加评论
    $("#addContentBtn").click(function(){
        //获取昵称和评论内容
        let nickName = $("#nickName").val();
        let content = $("#content").val();
        if(!nickName || !content){
            alert("请将信息填写完整");
            return;
        }
        let obj = {
            nickName, content, dateTime:new Date()
        }
        console.log(obj);
        //添加评论信息
        $.ajax({
            url: "http://localhost:3000/commonts",
            type: "POST",
            data: obj,
            success: function(data){
                render();
                $("#nickName").val("");
                $("#content").val("");
                setTimeout(()=>{
                    alert("发表成功！");
                },100);
            }
        }) 
    })

    // 删除评论
    function deleteCommont(id){
        if(confirm("确定删除吗？")){
            $.ajax({
                url: "http://localhost:3000/commonts/"+id,
                type: "DELETE",
                data: {
                    "id": id
                },
                success: function(data){
                    render();
                }
            })
        }  
    }

</script>
</html>